import { fileURLToPath, URL } from "node:url"

import { defineConfig, loadEnv } from "vite"
import vue from "@vitejs/plugin-vue"
import vueDevTools from "vite-plugin-vue-devtools"
// element-plus按需导入
import AutoImport from "unplugin-auto-import/vite"
import Components from "unplugin-vue-components/vite"
import { ElementPlusResolver } from "unplugin-vue-components/resolvers"
// 引入svg需要用到的插件
import { createSvgIconsPlugin } from "vite-plugin-svg-icons"
import path from "path"
// mock插件提供的方法
import { viteMockServe } from "vite-plugin-mock"

// https://vite.dev/config/
export default defineConfig(({ command, mode }) => {
  // 获取环境变量
  let env = loadEnv(mode, process.cwd())
  return {
    plugins: [
      vue(),
      vueDevTools(),
      // element相关配置
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      // svg相关
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
        symbolId: "icon-[dir]-[name]",
      }),
      // mock相关
      viteMockServe({
        localEnabled: command === "serve",
        // enable: command === 'serve',
      }),
    ],
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    // scss全局变量配置
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          // additionalData: '@import "./src/styles/variable.scss";',
          additionalData: `@use "@/styles/variable.scss" as *;`,
        },
      },
    },
    // 代理跨域
    server: {
      proxy: {
        [env.VITE_APP_BASE_API]: {
          // 获取数据的服务器地址设置
          target: env.VITE_SERVE,
          // 是否需要代码跨域
          changeOrigin: true,
          // 路径重写
          rewrite: (path) => path.replace(/^\/dev-api/, ""),
        },
      },
    },
  }
})
